package com.jhondge.skia;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import com.jhondge.skia.view.SkiaView;

import android.app.Activity;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class SkiaDemoActivity extends Activity {

	public static final String SDCARD_SKIA_DEMO = "/sdcard/skia_demo/";
	private static final String TAG = SkiaDemoActivity.class.getSimpleName();
	private SkiaView mSkiaView;

	private ImageView bitImageView;
	private LinearLayout layout;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		copyAssetFileToSDCard();
		mSkiaView = new SkiaView(this);
		setContentView(R.layout.main);
		layout = (LinearLayout) findViewById(R.id.skiaViewLayout);
		LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.FILL_PARENT);
		layout.addView(mSkiaView,layoutParams);
		bitImageView = (ImageView) findViewById(R.id.loadBitmap);
		Bitmap bm = mSkiaView.loadBitmap(SDCARD_SKIA_DEMO + "test.jpg");
		try {
			bm.compress(CompressFormat.JPEG, 80, new FileOutputStream("/sdcard/skia.jpg"));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		bitImageView.setImageBitmap(bm);
	}

	@Override
	public void finish() {
		mSkiaView.finish();
		super.finish();
	}

	private void copyAssetFileToSDCard() {
		try {
			AssetManager assetManager = getResources().getAssets();
			String[] fileNames = assetManager.list("fx");
			File fileDir = new File(SDCARD_SKIA_DEMO);
			if (!fileDir.exists())
				fileDir.mkdirs();
			for (int i = 0; i < fileNames.length; i++) {
				InputStream is = assetManager.open("fx/" + fileNames[i]);
				write2SDCard(is, SDCARD_SKIA_DEMO + fileNames[i]);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void write2SDCard(InputStream is, String filePath)
			throws IOException {
		Log.d(TAG, "write file to :" + filePath);
		byte[] buffer = new byte[4 * 1024];
		File file = new File(filePath);

		FileOutputStream outputStream = new FileOutputStream(file);
		float count = is.available();
		int len = 0;
		int progress = 0;
		while ((len = is.read(buffer)) != -1) {
			outputStream.write(buffer, 0, len);
			progress += len;
			Log.d(TAG, "progress/count:" + progress + "/" + count + "="
					+ (progress / count * 100) + "%");
		}
		is.close();
		outputStream.close();
	}
}